package blog.spring.web.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import blog.core.exception.FormParamErrorException;
import blog.core.exception.NotFoundException;
import blog.spring.db.dao.IArticleDAO;
import blog.spring.db.entity.ArticleInfo;
import blog.spring.db.entity.CmsUser;
import blog.spring.db.entity.Comment;
import blog.spring.db.entity.Lable;
import blog.spring.db.entity.User;
import blog.spring.db.service.IArticleService;
import blog.spring.db.service.ICommentService;
import blog.spring.db.service.ILableService;
import blog.spring.db.service.ITypeService;
import blog.spring.db.service.IUserService;
import blog.spring.db.service.impl.TypeService.DescribeType;
import blog.spring.web.entity.Result;
import blog.spring.web.util.CookieUtils;

@Controller
@RequestMapping("/article")
public class ArticleController extends BlogController {

	private final static String CURRENT_DIR = "article";

	public ArticleController() {
		super(CURRENT_DIR);
	}

	@Resource
	private IUserService userService;
	@Resource
	private IArticleService articleService;
	@Resource
	private ITypeService typeService;
	@Resource
	private ILableService lableService;
	@Resource
	private IArticleDAO articleDao;
	@Resource
	private ICommentService commentService;

	/***************** 添加文章 *****************/
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(ModelMap map) {
		map.addAttribute("types",
				typeService.getTypeListAll(DescribeType.ARTICLE));
		map.addAttribute("lables", lableService.findAll());
		return "article/add";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(ArticleInfo info, HttpServletRequest req, ModelMap map) {
		User curUser = CookieUtils.isLogin(req, userService);
		if (curUser == null)
			return "article/add";
		info.setUser(curUser);
		try {
			articleService.save(info);
		} catch (FormParamErrorException e) {
			addException(map, e);
			map.addAttribute("info", info);
			map.addAttribute("types",
					typeService.getTypeListAll(DescribeType.ARTICLE));
			map.addAttribute("lables", lableService.findAll());
			return "article/add";
		}
		return redirectIndex();
	}

	/***************** 获取文章及内容 *****************/
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String get(@PathVariable("id") int id, ModelMap map) {
		map.addAttribute("info", articleService.findById(id));
		return forwardCurentInfo();
	}
	/***************** 获取文章评论列表[JSON] *****************/
	@RequestMapping(value = "/{id}/comments", method = RequestMethod.GET)
	public @ResponseBody List<Comment> getComment(@PathVariable("id") int id) {
		return articleService.getComments(id);
	}

	/***************** 评论文章 *****************/
	@RequestMapping(value = "/{id}", method = RequestMethod.POST)
	public String get(@PathVariable("id") int id, Comment comment, ModelMap map) {
		articleService.findById(id);
		User user = comment.getUser();
		user.setCmsUser(new CmsUser());
		try {
			userService.save(user);
			comment.setUser(new User(user.getUserId()));
			comment.setArticleInfo(new ArticleInfo(id));
			commentService.save(comment);
		} catch (FormParamErrorException e) {
			addException(map, e);
			return forwardCurentInfo();
		}
		return redirect("/article/" + id);
	}

	/***************** 获取热门文章列表 *****************/
	@RequestMapping(value = "/hot", method = RequestMethod.GET)
	public @ResponseBody List<ArticleInfo> hot(ModelMap map) {
		return articleService.findHot(5);
	}

	/***************** 删除文章及内容 *****************/
	@RequestMapping(value = "/remove/{id}", method = RequestMethod.GET)
	public String remove(@PathVariable("id") int id, ModelMap map) {
		ArticleInfo info = articleService.findById(id);
		if (info != null)
			articleService.remove(info);
		return redirectIndex();
	}

	/***************** 修改文章 *****************/
	@RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
	public String update(@PathVariable("id") int id, ModelMap map) {

		ArticleInfo info = articleService.findById(id);
		map.addAttribute("info", info);
		map.addAttribute("types",
				typeService.getTypeListAll(DescribeType.ARTICLE));
		return forwardCurentUpdate();
	}

	@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
	public String update(@PathVariable("id") int id, ArticleInfo info,
			HttpServletRequest req, ModelMap map) {
		User curUser = CookieUtils.isLogin(req, userService);
		if (curUser == null)
			return forwardCurentUpdate();
		info.setUser(curUser);
		info.setArticleId(id);
		try {
			articleService.update(info);
		} catch (FormParamErrorException e) {
			addException(map, e);
			return forwardCurentUpdate();
		}
		return redirectIndex();
	}

	/***************** 文章追加 *****************/
	@RequestMapping(value = "/addTo/{id}", method = RequestMethod.GET)
	public String addTo(@PathVariable("id") int id, ModelMap map) {
		ArticleInfo info = articleService.findById(id);
		map.addAttribute("info", info);
		map.addAttribute("lables", lableService.findAll());
		return CURRENT_DIR + "/addTo";
	}

	@RequestMapping(value = "/addTo/{id}", method = RequestMethod.POST)
	public String addTo(@PathVariable("id") int id, String addContent,
			HttpServletRequest req, ModelMap map) {
		User curUser = CookieUtils.isLogin(req, userService);
		if (curUser == null)
			return CURRENT_DIR + "/addTo";
		try {
			articleService.addTo(id, addContent);
		} catch (FormParamErrorException e) {
			addException(map, e);
			return CURRENT_DIR + "/addTo";
		}
		return redirectIndex();
	}

	/***************** 标签的追加[JSON] *****************/
	@RequestMapping(value = "/lable/add/{id}", method = RequestMethod.POST)
	public @ResponseBody Result addLable(@PathVariable("id") int id,
			ArrayList<Lable> lables, ModelMap map) {
		ArticleInfo info = articleService.findById(id);
		List<Lable> originalLables = info.getLables();
		List<Lable> addLables = new ArrayList<Lable>();
		for (Lable lable : lables) {
			try {
				addLables.add(lableService.findById(lable.getLableId()));
			} catch (NotFoundException e) {
				return new Result(NotFoundException.HTTP_STATUS, "标签:"
						+ lable.getTitle() + "不存在");
			}
		}
		for (Lable lable : addLables) {
			if (originalLables.contains(lable))
				continue;
			originalLables.add(lable);
		}
		articleDao.update(info);
		return Result.SUCCESS();
	}

	/***************** 标签的更新[JSON] *****************/
	@RequestMapping(value = "/lable/update/{id}", method = RequestMethod.POST)
	public @ResponseBody Result updateLable(@PathVariable("id") int id,
			ArrayList<Lable> lables, ModelMap map) {
		ArticleInfo info = articleService.findById(id);
		List<Lable> addLables = new ArrayList<Lable>();
		for (Lable lable : lables) {
			try {
				addLables.add(lableService.findById(lable.getLableId()));
			} catch (NotFoundException e) {
				return new Result(NotFoundException.HTTP_STATUS, "标签:"
						+ lable.getTitle() + "不存在");
			}
		}
		info.setLables(addLables);
		return Result.SUCCESS();
	}
}
